<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <el-row :gutter="10" class="mb8" ref="hMain">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="treeHandleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="el-icon-edit" size="mini" @click="treeHandleUpdate">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="el-icon-delete" size="mini" @click="treeHandleDelete">删除</el-button>
          </el-col>
        </el-row>

        <div class="head-container"  :style="{height:treeHeight+'px'}"  style="overflow: auto">
          <el-tree :data="deptOptions" :props="defaultProps" :expand-on-click-node="false" ref="tree" node-key="id"
                   default-expand-all highlight-current @node-click="handleNodeClick" :filter-node-method="filterNode"
                   :default-expanded-keys="expandedkeys" :current-node-key="currentNodekey" :style="isSize">
            <template slot-scope="{ node, data }">
              <span class="span-ellipsis" :title="node.label" :style="isSize">{{ node.label }}</span>
            </template>
          </el-tree>
        </div>
      </el-col>

      <el-col :span="20" :xs="24" v-show="isShow">
        <el-row :gutter="10" class="mb8" ref="refbut">
          <el-col :span="1.5">
            <el-button type="primary" plain size="mini" icon="el-icon-plus"  @click="handeleAdd">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain size="mini" icon="el-icon-edit"  @click="handeleUpdate">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain size="mini" icon="el-icon-delete"  @click="handeleDelete">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain size="mini" icon="el-icon-upload2"  @click="handleImport">导入</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" size="mini" plain icon="el-icon-download"  @click="handldExport">导出</el-button>
          </el-col>
        </el-row>
        <el-table v-loading="loading" :data="DataList" :height="tableHeight" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="序号" type="index" :index="table_index" align="center" />
          <el-table-column label="类号名称" prop="categoryName" align="center" />
          <el-table-column label="类号" prop="categoryCode" align="center" />
          <el-table-column label="备注" prop="remarks" align="center" />
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize" @pagination="getList" />
      </el-col>
      <el-col :span="20" :xs="24" v-show="!isShow" class="empty">
        <el-empty :image-size="200"></el-empty>
      </el-col>
    </el-row>

    <!-- 树节点添加及修改 -->
    <el-dialog :title="treeTitle" :visible.sync="treeOpen" width="30%" append-to-body>
      <div>
        <el-form ref="treeForm" :rules="treeRules" :model="treeForm" label-width="80px">
          <el-form-item label="类别名称" prop="dataName">
            <el-input v-model="treeForm.dataName" placeholder="请输入类别名称"></el-input>
          </el-form-item>
          <el-form-item label="类别代码" prop="dataCode">
            <el-input v-model="treeForm.dataCode" placeholder="请输入类别代码"></el-input>
          </el-form-item>
          <el-form-item label="顺序" prop="orderNum">
            <el-input-number v-model="treeForm.orderNum" controls-position="right" style="width: 100%" :min="1" placeholder="请输入排序号"></el-input-number>
          </el-form-item>
          <el-form-item label="备注" prop="remarks">
            <el-input v-model="treeForm.remarks" type="textarea" :rows="2" placeholder="请输入备注" ref="treeTextRef"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitTreeForm">确 定</el-button>
        <el-button @click="cancelTreeForm">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 类号添加及修改 -->
    <el-dialog :title="title" :visible.sync="open" width="30%" append-to-body>
      <div>
        <el-form ref="form" :rules="rules" :model="form" label-width="120px">
          <el-form-item label="类号名称" prop="categoryName">
            <el-input v-model="form.categoryName" placeholder="请输入类别名称"></el-input>
          </el-form-item>
          <el-form-item label="类号代码" prop="categoryCode">
            <el-input v-model="form.categoryCode" placeholder="请输入类别代码"></el-input>
          </el-form-item>
          <el-form-item label="顺序" prop="orderNum">
            <el-input-number v-model="form.orderNum" controls-position="right" style="width: 100%" :min="1" placeholder="请输入排序号"></el-input-number>
          </el-form-item>
          <el-form-item label="默认控制属性" prop="controlType">
            <el-select v-model="form.controlType" placeholder="请选择" clearable style="width: 100%">
              <el-option v-for="dict in dict.type.CONTROLTYPE" :key="dict.value" :label="dict.label"
                         :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="remarks">
            <el-input v-model="form.remarks" type="textarea" :rows="2" placeholder="请输入备注" ref="textareaRef"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancelForm">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :on-change="handleChange" :file-list="fileList" accept=".xlsx, .xls" :headers="upload.headers"
                 :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
                 :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                   @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import estimateTableHeight from "@/mixins/estimateTableHeight";
import {
  addCode,
  addTree, detailCode, detailTree, getCodeDetail, getTableList,
  getTreeDetail,
  getTreeList, updateCode,
  updateTree
} from "@/api/information/applicationManagement/dataTreeManagement";
import {getToken} from "@/utils/auth";

export default {
  name: "index",
  mixins: [estimateTableHeight], // 混入方法
  archive_Dicts: ['CONTROLTYPE'],
  data() {
    const checkDataCode = (rule, value, callback) => {
      if (value) {
        var reg = /^[A-Z]$/
        if (reg.test(value) == false) {
          callback(new Error('请输入一位大写字母'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    const checkCategoryCode = (rule, value, callback) => {
      if (value) {
        var reg = /^[A-Z]\d{3}$/
        if (reg.test(value) === false) {
          callback(new Error('请输入1位大类别号+3位数字格式的类号'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      // 部门树选项
      deptOptions: undefined,
      defaultProps: {
        children: "children",
        label: "label"
      },
      //默认展开的树节点
      expandedkeys: [],
      //默认选中的树节点
      currentNodekey: "",
      isShow: false,
      isnoClick:true,

      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      name: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      DataList: [],
      total: 0,

      treeTitle: '',
      treeOpen: false,
      // 树表单校验
      treeRules: {
        dataName: [
          { required: true, message: '请输入类别名称', trigger: 'blur' },
        ],
        dataCode: [
          { required: true, message: '请输入类别代码', trigger: 'blur' },
          { required: true, trigger: 'blur', validator: checkDataCode }
        ],
        orderNum: [
          { required: true, message: '请输入顺序', trigger: 'blur' },
        ],
      },
      // 树表单参数
      treeForm: {
        dataName: undefined,
        dataCode: undefined,
        orderNum: undefined,
        remarks: undefined
      },

      title: '',
      open: false,
      // 表单校验
      rules: {
        categoryName: [
          { required: true, message: '请输入类号名称', trigger: 'blur' },
        ],
        categoryCode: [
          { required: true, message: '请输入类号代码', trigger: 'blur' },
          { required: true, trigger: 'blur', validator: checkCategoryCode }
        ],
        controlType: [
          { required: true, message: '请输入默认控制属性', trigger: 'blur' }
        ],
        orderNum: [
          { required: true, message: '请输入顺序', trigger: 'blur' },
        ],
      },
      // 表单参数
      form: {
        categoryName: undefined,
        categoryCode: undefined,
        controlType: undefined,
        orderNum: undefined,
        remarks: undefined
      },

      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的基础数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/archive/collection/data/category/importData"
      },
      fileList: []
    }
  },
  computed: {
    isSize() {
      if (this.$store.getters.size == 'small') {
        this.size = 'font-size: 12px;'
      } else {
        this.size = 'font-size: 14px;'
      }
      return this.size
    }
  },
  created() {
    this.getDeptTree()
  },
  methods: {
    /** 查询树结构 */
    getDeptTree() {
      this.deptOptions = []
      getTreeList().then(response => {
        const rootNode = { id: 'root', label: '馆藏资料', children: [] };
        const otherNodes = response.rows.map(item => {
          return {
            id: item.id,
            label: item.dataName + '(' + item.dataCode + ')',
            treeCode: item.dataCode
          }
        })
        rootNode.children = otherNodes;
        this.deptOptions.push(rootNode)
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      if(this.isnoClick) {
        console.log(data)
        this.isnoClick=false;
        this.treeId = data.id
        this.label = data.label
        if(data.id == 'root') {
          this.isShow = false
          this.isnoClick=true;
        } else {
          this.isShow = true
          this.queryParams.treeCode = data.treeCode
          this.getList()
        }
      } else {
        this.$message({ message: '重复点击，请稍后再试!', type: 'warning' })
      }
    },
    // 增加树节点
    treeHandleAdd() {
      if(this.treeId == 'root') {
        this.resetForm('treeForm')
        this.reset()
        this.treeTitle = '添加资料类别'
        this.treeOpen = true
      } else {
        this.$message({ message: '只能在馆藏节点下新增类别节点哦', type: 'warning'})
      }
    },
    // 修改树节点
    treeHandleUpdate() {
      if(this.treeId == undefined || this.treeId == 'root') {
        this.$message({ message: '请选择馆藏节点下任一类别节点进行修改', type: 'warning'})
      } else {
        this.resetForm('treeForm')
        this.reset()
        getTreeDetail(this.treeId).then(response=>{
          this.treeForm = response.data
          this.treeTitle = '修改资料类别'
          this.treeOpen = true
        })
      }
    },
    submitTreeForm() {
      this.$refs["treeForm"].validate((valid) => {
        if(valid) {
          if(this.treeForm.id != undefined) {
            updateTree(this.treeForm).then(response=>{
              this.$modal.msgSuccess("修改成功");
              this.treeOpen = false;
              this.getDeptTree();
            })
          } else {
            addTree(this.treeForm).then(response=>{
              this.$modal.msgSuccess("新增成功");
              this.treeOpen = false;
              this.getDeptTree();
            })
          }
        }
      })
    },
    // 关闭树弹窗
    cancelTreeForm() {
      this.treeOpen = false
    },
    // 删除树节点
    treeHandleDelete() {
      if(this.treeId == undefined || this.treeId == 'root') {
        this.$message({ message: '请选择馆藏节点下任一类别节点进行删除', type: 'warning'})
      } else {
        this.$modal.confirm('是否确认删除选中类别名称为"'+ this.label +'"的数据项？').then(function () { }).then(() => {
          detailTree(this.treeId).then(res => {
            if (res.code == "200") {
              this.$modal.msgSuccess("删除成功");
              this.getDeptTree();
              this.isShow = false
            }
          })
        }).catch(() => { });
      }
    },
    table_index(index){
      return (this.queryParams.pageNum-1) * this.queryParams.pageSize + index + 1;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.name = selection.map(item => item.categoryName)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    getList() {
      getTableList(this.queryParams).then(response=>{
        this.DataList = response.rows
        this.total = response.total
        this.loading = false
        this.isnoClick=true;
      })
    },
    reset() {
      // 树表单参数
      this.treeForm = {
        dataName: undefined,
        dataCode: undefined,
        orderNum: undefined,
        remarks: undefined
      }
      this.form = {
        categoryName: undefined,
        categoryCode: undefined,
        controlType: undefined,
        orderNum: undefined,
        remarks: undefined
      }
      this.$nextTick(() => {
        if ( this.$refs.textareaRef != undefined) {
          this.$refs.textareaRef.$refs.textarea.style.height = 'auto'; // 重置高度
        }
        if (this.$refs.treeTextRef != undefined) {
          this.$refs.treeTextRef.$refs.textarea.style.height = 'auto'; // 重置高度
        }
      });
    },
    // 类号新增
    handeleAdd() {
      this.resetForm('form')
      this.reset()
      if(this.queryParams.treeCode == 'A' || this.queryParams.treeCode == 'B') {
        this.$set(this.form, 'controlType', '1')
      } else {
        this.$set(this.form, 'controlType', '0')
      }
      this.title = '新增资料类号'
      this.open = true
    },
    // 类号修改
    handeleUpdate(row) {
      this.resetForm('form')
      this.reset()
      const id = row.id || this.ids
      if(id.length == 0 || id.length > 1) {
        this.$modal.msgWarning('请选择一条数据进行修改')
      } else {
        getCodeDetail(id.toString()).then(response=>{
          this.form = response.data
          this.title = '修改资料类号'
          this.open = true
        })
      }
    },
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if(valid) {
          const str = this.form.categoryCode.substring(0, 1);
          if(str != this.queryParams.treeCode) {
            this.$modal.msgWarning('请输入对应的大类别号'+ this.queryParams.treeCode + ' + 三位数字的组合样式')
            return
          }
          if(this.form.id != undefined) {
            updateCode(this.form).then(response=>{
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            })
          } else {
            this.form.treeCode = this.queryParams.treeCode
            addCode(this.form).then(response=>{
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            })
          }
        }
      })
    },
    cancelForm() {
      this.open = false
    },
    // 类号删除
    handeleDelete(row) {
      const id = row.id || this.ids
      console.log(id, id.toString())
      if(id.length == 0) {
        this.$modal.msgWarning('请选择至少一条数据进行删除')
      } else {
        this.$modal.confirm('是否确认删除选中类号名称为"'+ this.name +'"的数据项？').then(function () { }).then(() => {
          detailCode(id.toString()).then(res => {
            if (res.code == "200") {
              this.$modal.msgSuccess("删除成功");
              this.getList();
            }
          })
        }).catch(() => { });
      }
    },
    // 类号导入
    handleImport() {
      this.upload.title = "资料类号导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    handleChange(file, fileList) {
      this.fileList = []
      let length = fileList.length
       this.fileList = [fileList[length - 1]]
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
  
      this.$nextTick(()=>{

this.$refs.upload.clearFiles()

})
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('/archive/collection/data/category/importTemplate', {
      }, `information_template_${new Date().getTime()}.xlsx`)
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 类号导出
    handldExport(row) {
      const ids = row.id || this.ids;
      this.queryParams.ids=ids.toString();
      this.download('/archive/collection/data/category/export', {
        ...this.queryParams
      }, `information_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
